import Base from '@/components/Base';
import { View, Text } from '@/components/KayUI';
import { Slider, Input } from 'antd';
import DragArea from '@/components/DragArea';
import cx from 'classnames';
import React from 'react';
import styles from './index.less';

interface HSL {
  H: number; //色相   0-360
  S: number; //饱和度 0-100
  L: number; //亮度   0-100
}
interface RGB {
  R: number;
  G: number;
  B: number;
}

interface Props extends React.HTMLAttributes<HTMLDivElement> {
  onColorChange?: (obj: { hsl: HSL }) => void;
  value?: { hsl: number[] }; // [H,S,L]
}
interface States {
  hsl: HSL;
  rgb: RGB;
  // dragAreaVal: {persentX: number, persentY:number}
}

export default class ColorSelector extends Base<Props, States> {
  public state: States = {
    hsl: {
      H: 0,
      S: 100,
      L: 50,
    },
    rgb: {
      R: 0,
      G: 0,
      B: 0,
    },
    // dragAreaVal: {
    //   persentX: 0,
    //   persentY: 0
    // }
  };

  private propValueHsl = (nextProp?: any) => {
    const value = nextProp ? nextProp.value : this.props.value;
    if (value && value.hsl) {
      return {
        H: value.hsl[0] || 0,
        S: value.hsl[1] || 100,
        L: value.hsl[2] || 50,
      };
    } else {
      return null;
    }
  };
  private setProsHsl = (nextProp?: any) => {
    const val = this.propValueHsl(nextProp);
    if (val) {
      this.setState({
        hsl: val,
      });
    }
  };

  public didMount() {
    this.setProsHsl();
  }

  public componentWillReceiveProps(nextProps: any) {
    const { hsl } = this.state;
    if (
      nextProps.hasOwnProperty('value') &&
      JSON.stringify(hsl) != JSON.stringify(nextProps.value.hsl)
    ) {
      // console.log("我丢", hsl, nextProps.value, nextProps.hasOwnProperty('value'))
      this.setProsHsl(nextProps);
    }
  }

  public render() {
    const {
      className,
      children,
      onColorChange, //保证restProps不包含自定义的props，自定义的props不能直接传给div
      ...restProps
    } = this.props;
    const { hsl, rgb } = this.state;

    return (
      <View className={cx(styles.main, className)} {...restProps}>
        <View className={styles.top}>
          <View
            className={styles.background}
            style={{
              // background: this.getCurrentColor
              background: this.interface.Color(
                'hsl(' + hsl.H + ' ' + '100% 50%)',
              ),
            }}
          >
            <View className={styles.bgLayerWhite}>
              <DragArea
                className={styles.bgLayerBlack}
                value={this.dragAreaValue}
                onChangePosition={this.handleDrag}
              ></DragArea>
            </View>
          </View>
        </View>
        <View className={styles.bottom}>
          <View className={styles.slidBox}>
            <Slider
              min={0}
              max={360}
              step={1}
              value={hsl.H}
              tooltipVisible={false}
              railStyle={{
                height: 10,
                top: 1,
                borderRadius: 100,
                backgroundImage:
                  'linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%)',
                // backgroundImage: `-webkit-linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%)`,
              }}
              trackStyle={{
                background: 'transparent',
              }}
              handleStyle={{
                background: '#fff',
                border: 'none',
                outline: 'none',
                boxShadow: '0 0 0 4px rgba(0,0,0,0.1)',
              }}
              onChange={(e) => {
                this.changeHsl('H', e);
              }}
            />
          </View>
          <View className={cx(styles.rowCenter, styles.inputGroup)}>
            <View className={styles.inputBox}>
              <Text className={styles.adBefore}>H</Text>
              <Input
                className={styles.input}
                value={hsl.H}
                size="small"
                onChange={this.changeHsl.bind(this, 'H')}
              />
            </View>
            <View className={styles.inputBox}>
              <Text className={styles.adBefore}>S</Text>
              <Input
                className={styles.input}
                value={hsl.S}
                size="small"
                onChange={this.changeHsl.bind(this, 'S')}
              />
              <Text className={styles.adAfter}>%</Text>
            </View>
            <View className={styles.inputBox}>
              <Text className={styles.adBefore}>L</Text>
              <Input
                className={styles.input}
                value={hsl.L}
                size="small"
                onChange={this.changeHsl.bind(this, 'L')}
              />
              <Text className={styles.adAfter}>%</Text>
            </View>
          </View>
          <View className={cx(styles.rowCenter, styles.inputGroup)}>
            <View className={styles.inputBox}>
              <Text className={styles.adBefore}>R</Text>
              <Input
                className={styles.input}
                value={rgb.R}
                size="small"
                onChange={this.changeRgb.bind(this, 'R')}
              />
            </View>
            <View className={styles.inputBox}>
              <Text className={styles.adBefore}>G</Text>
              <Input
                className={styles.input}
                value={rgb.G}
                size="small"
                onChange={this.changeRgb.bind(this, 'G')}
              />
            </View>
            <View className={styles.inputBox}>
              <Text className={styles.adBefore}>B</Text>
              <Input
                className={styles.input}
                value={rgb.B}
                size="small"
                onChange={this.changeRgb.bind(this, 'B')}
              />
            </View>
          </View>
        </View>
      </View>
    );
  }
  // private getCurrentColor() {
  //   const { hsl } = this.state;
  //   return this.interface.Color('hsl(' + hsl.H + ' ' + hsl.S + '% ' + hsl.L + '%)');
  // }
  private changeHsl = (key, value) => {
    if (typeof value === 'object' && value.target) {
      value = value.target.value;
    }
    this.changeHslMult({ [key]: value });
  };
  private changeHslMult = (obj: any) => {
    const hsl = {
      ...this.state.hsl,
      ...obj,
    };
    this.setState(
      {
        hsl,
      },
      this.handleSubmit,
    );

    const rgb = this.HslToRgb(hsl); //
    this.changeRgbMult(rgb);
  };

  private changeRgb = (key, value) => {
    if (typeof value === 'object' && value.target) {
      value = value.target.value;
    }
    this.changeRgbMult({ [key]: value });
  };
  private changeRgbMult = (obj: any) => {
    this.setState({
      rgb: {
        ...this.state.rgb,
        ...obj,
      },
    });
  };

  private HslToRgb = (hsl: HSL) => {
    const rgbObj = this.interface.Color.hsl(hsl.H, hsl.S, hsl.L).rgb().object();
    return {
      R: parseInt(rgbObj.r),
      G: parseInt(rgbObj.g),
      B: parseInt(rgbObj.b),
    };
  };
  private RgbToHsl = (rgb: RGB) => {
    const rgbObj = this.interface.Color.rgb(rgb.R, rgb.G, rgb.B).hsl().object();
    return {
      H: parseInt(rgbObj.h),
      S: parseInt(rgbObj.s),
      L: parseInt(rgbObj.l),
    };
  };

  private get dragAreaValue() {
    //根据HSL的饱和度、明度反推DragArea的persentX/Y
    const { hsl } = this.state;
    return {
      persentX: hsl.S,
      persentY: ((200 - hsl.S - hsl.L * 2) * 100) / (200 - hsl.S),
    };
  }
  private handleDrag = (res: any) => {
    // x: res.persentX %
    // y: res.persentY %
    if (res) {
      this.changeHslMult({
        S: parseInt(res.persentX),
        L: parseInt(
          String(
            (100 - res.persentY + 100 - res.persentX) * 0.5 -
              ((100 - res.persentX) / 100) * res.persentY * 0.5,
          ),
        ),
      });
      /**
       * Lightness:
       * 100   75    50
       * 50          25
       * 00000000000000
       * ((100-x)+(100-y))*0.5 -  ((100-x)/100 * y*0.5)
       * **/
    }
  };

  private handleSubmit = () => {
    const { hsl } = this.state;
    const co = this.interface.Color(
      'hsl(' + hsl.H + ' ' + hsl.S + '% ' + hsl.L + '%)',
    );
    console.log(hsl, co, co.rgb().array(), co.rgb().object());
    const { onColorChange } = this.props;
    if (onColorChange) {
      onColorChange({
        hsl,
      });
    }
  };
}
